package com.truonghau.smstoxls.receiver;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;

import com.truonghau.xmeasure.commons.Constants;
import com.truonghau.xmeasure.commons.SmSUtils;

public class IncomingSmsBroadcastReceiver extends BroadcastReceiver {

	private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
	//private static final String SMS_FORMAT = "XKDX";
	private static final String NOTIF_OK_DONE = "Đã nhận tin nhắn doanh số";
	private static boolean isTheFirst = true;
	private NotificationManager mNM;
	@Override
	public void onReceive(final Context context, final Intent intent) {
		//co 1 tin nhan toi la Run
		if (intent != null && SMS_RECEIVED.equals(intent.getAction())) {
			//notifi

			final SmsMessage smsMessage = extractSmsMessage(intent);
			if(smsMessage != null ){
				String str = smsMessage.getMessageBody();
				str = str.replace(";", ":");
				String[] arr = str.split(":");
				String SMS_FORMAT = getFormatSms(context).toUpperCase(); 
				if(arr != null && SMS_FORMAT.equals(arr[0].trim().toUpperCase())){
					mNM = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
					SmSUtils.processMessage(context, smsMessage);
					SmSUtils.showNotification(context, mNM, NOTIF_OK_DONE);
				}else {
					//neu khop voi format 2
				}
			}
		}
		if(isTheFirst){
			SmSUtils.startSMSAlert(context);
			isTheFirst = false;
		}

	}

	private String getFormatSms(final Context context){
		SharedPreferences settings = context.getSharedPreferences(
				Constants.PREFS_NAME, 0);
		return settings.getString(Constants.TxtMsgFormat1, "");
	}
	private SmsMessage extractSmsMessage(final Intent intent) {

		final Bundle pudsBundle = intent.getExtras();
		final Object[] pdus = (Object[]) pudsBundle.get("pdus");
		final SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);

		return smsMessage;

	}

}
